<?php
namespace hema\wechat;

use app\common\model\Config;
use app\common\model\Applet;
use app\common\model\Wechat;
use app\common\model\Setting;
use hema\Http;
use think\facade\Cache;

class Driver
{
	private $config;
    private $error;

	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$this->config = Config::detail();
	}
	
	/**
     * 获取session_key - 非服务商版
    */
    public function getSessionKey(string $code, $applet)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $queryarr = [
            'appid' => $applet['app_id'],
            'secret' => $applet['app_secret'],
            'grant_type' => 'authorization_code',
            'js_code' => $code
        ];
        $result = json_decode(Http::get($url, $queryarr),true);
        if (isset($result['errcode'])) {
            $this->error = 'code：' . $result['errcode'] . ' msg：' . $result['errmsg'];
            return false;
        }
        return $result;
    }

    /**
     * 获取session_key - 服务商版
     */
    public function getComponentSessionKey(string $code, int $applet_id = 0)
    {
        $applet = Applet::getApplet(['applet_id' => $applet_id]);
        $url = 'https://api.weixin.qq.com/sns/component/jscode2session';
        $queryarr = [
            'appid' => $applet['app_id'],
            'js_code' => $code,
            'grant_type' => 'authorization_code',
            'component_appid' => $this->config['app_id'],
            'component_access_token' => $this->config['component_access_token']
        ];
        $result = json_decode(Http::get($url, $queryarr),true);
        if (isset($result['errcode'])) {
            $this->error = 'code：' . $result['errcode'] . ' msg：' . $result['errmsg'];
            return false;
        }
        return $result;
    }
    
    /**
     * 公众号用户登录 code 换取 access_token
     * $appid  公众号的APPID
     */
    public function oauth2($code,$appid,$applet_id)
    {
        $access_token = $this->getAccessToken($applet_id,2);
        //通过 code 换取 access_token
        $url = 'https://api.weixin.qq.com/sns/oauth2/component/access_token';
        $queryarr = [
            'appid' => $appid,
            'code' => $code,
            'grant_type' => 'authorization_code',
            'component_appid' => $this->config['app_id'],
            'component_access_token' => $this->config['component_access_token']
        ];
        $result = json_decode(Http::get($url, $queryarr),true);
        if (isset($result['errcode'])) {
            $this->error = 'code：'.$result['errcode'].'，msg：' . $result['errmsg'];
            return false;
        }
        return $result;
    }
	
	

	
	






    

    /**
    * 公众号获取粉丝列表
    */
    public function getFans(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id,2);
        $url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&next_openid=';
        $result = json_decode(Http::get($url),true);
        return $result;
    }

    /**
     * 提交微信小程序申请
     */
    public function fastRegisterWeApp($data)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=create&component_access_token=' . $this->config['component_access_token'];
        $queryarr =[
            'name' => $data['merchant_name'],     //营业执照名称
            'code' => $data['license_number'], //统一社会信用代码
            'code_type' => 1,   // 企业代码类型（1：统一社会信用代码， 2：组织机构代码，3：营业执照注册号）
            'legal_persona_wechat' => $data['legal_persona_wechat'], //所有人微信
            'legal_persona_name' => $data['id_card_name'],  //所有人姓名
            'component_phone' => '' //第三方联系电话
        ];
        $result = json_decode(Http::post($url,json_encode($queryarr,JSON_UNESCAPED_UNICODE)),true);
        return $result;
    }

    /**
     * 获取指定版本的审核状态 - 小程序代码模板
     */
    public function getAuditStatus($applet_id,$auditid)
    {
        $access_token = getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/get_auditstatus?access_token='.$access_token;
        $queryarr = [
            'auditid' => $auditid
        ];
        $result = json_decode(Http::post($url, json_encode($queryarr)),true);
        return $result; 
    }

    /**
     * 修改图文素材 - 到微信端
     */
    public function updateNews(array $data, int $media_id, int $applet_id = 0)
    {
        $access_token = $this->getAccessToken($applet_id,2);
        for($n=0;$n<sizeof($data);$n++){
            $queryarr = [
                'media_id' => $media_id,
                'index' => $data[$n]['ids'],
                'articles' => [
                    'title' => $data[$n]['title'],
                    'thumb_media_id' => $data[$n]['media_id'],
                    'author' => $data[$n]['author'],
                    'digest' => $data[$n]['digest'],
                    'show_cover_pic' => 1,
                    'content' => str_ireplace('"','\'',$data[$n]['wx_content']),
                    'content_source_url' => base_url()
                ]
            ];
            //上传到微信服务器
            $url = 'https://api.weixin.qq.com/cgi-bin/material/update_news?access_token='.$access_token;
            $result = json_decode(Http::post($url,json_encode($queryarr)),true);
            //return $result;
        }
        return true;
    }

    /**
     * 上传图文素材 - 到微信端
     */
    public function addNews(array $data, int $applet_id = 0)
    {
        $queryarr['articles'] = array();
        for($n=0;$n<sizeof($data);$n++){    
            array_push($queryarr['articles'],[
                'title' => $data[$n]['title'],
                'thumb_media_id' => $data[$n]['media_id'],
                'author' => $data[$n]['author'],
                'digest' => $data[$n]['digest'],
                'show_cover_pic' => 1,
                'content' => str_ireplace('"','\'',$data[$n]['wx_content']),
                'content_source_url' => base_url()
            ]);
        }
        $access_token = $this->getAccessToken($applet_id,2);
        //上传到微信服务器
        $url = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token='.$access_token;
        $result = json_decode(Http::post($url,json_encode($queryarr,JSON_UNESCAPED_UNICODE)),true);
        return $result;
    }

    /**
     * 上传图文消息内的图片 - 到微信端（永久素材） - 公众号端
     *  图片仅支持jpg/png格式，大小必须在1MB以下
     */
    public function upWechatUrl(array $img, int $applet_id = 0)
    {
        $access_token = $this->getAccessToken($applet_id,2);
        for($n=0;$n<sizeof($img);$n++){
            $real_path = web_path() . 'uploads/' . $img[$n]['file_path'];
            //上传到微信服务器
            $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token='.$access_token;
            $queryarr['media'] = curl_file_create($real_path,'image/jpeg',$img[$n]['file_path']);//获取要上传的二进制文件
            $result = json_decode(Http::post($url,$queryarr),true);
            if(!isset($result['url'])){
                return false;//上传错误，一般是图片不符合要求
            }
            $img[$n]['url'] = $result['url'];
        }
        return $img;
    }

    

    /**
     * 上传素材文件 - 到微信端
     */
    public function addMaterial(int $applet_id, string $file_path = '', int $file_type = 10, string $name = '', string $introduction = '')
    {
        // 验证文件并上传
        if($file_type==10){ //图片（image）: 2M，支持bmp/png/jpeg/jpg/gif格式
            $type = 'image';
            $mimetype = 'image/jpeg';
        }
        if($file_type==20){ //语音（voice）：2M，播放长度不超过60s，mp3/wma/wav/amr格式
            $type = 'voice';
            $mimetype = 'audio/mpeg';
        }
        if($file_type==30){ //视频（video）：10MB，支持MP4格式
            $type = 'video';
            $mimetype = 'video/mp4';
            $queryarr['description'] = '{"title":"'.$name.'","introduction":"'.$introduction.'"}';
        }
        $access_token = $this->getAccessToken($applet_id,2);
        $real_path = web_path() . 'uploads/' . $file_path;
        //上传到微信服务器
        $url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.$access_token.'&type='.$type;
        $queryarr['media'] = curl_file_create($real_path,$mimetype,$file_path);//获取要上传的二进制文件
        $result = json_decode(http_post($url,$queryarr),true);
        return $result;     //$result['media_id'];
    }

    /**
     * 删除素材文件 - 到微信端
     */
    public function delMaterial(string $media_id, int $applet_id = 0)
    {
        $access_token = $this->getAccessToken($applet_id,2);
        $url = 'https://api.weixin.qq.com/cgi-bin/material/del_material?access_token='.$access_token;
        $queryarr = [
            'media_id' => $media_id
        ];
        $result = json_decode(Http::post($url,json_encode($queryarr)),true);
        return $result;
    }

    /**
     * 根据OpenID列表群发公众号信息
     */
    public function sendMass($msg, $open_id, int $applet_id = 0)
    {
        //图文消息
        if($msg['msg_type']['value']=='news'){
            $queryarr = [
                'mpnews' => [
                    'media_id' => $msg['content']
                ],
                'msgtype' => 'mpnews',
                'send_ignore_reprint' => $msg['send_ignore_reprint']
            ];
        }
        //文本消息
        if($msg['msg_type']['value']=='text'){
            $queryarr = [
                'msgtype' => 'text',
                'text' => [
                    'content' => $msg['content']
                ]
            ];
        }
        //语音消息
        if($msg['msg_type']['value']=='voice'){
            $queryarr = [
                'voice' => [
                    'media_id' => $msg['content']
                ],
                'msgtype' => 'voice'
            ];
        }
        //图片消息
        if($msg['msg_type']['value']=='image'){
            $queryarr = [
                'images' => [
                    'media_ids' => [
                        0 => $msg['content']
                    ],
                    'recommend' => $msg['recommend'],
                    'need_open_comment' => $msg['need_open_comment'],
                    'only_fans_can_comment' => $msg['only_fans_can_comment']
                ],
                'msgtype' => 'image'
            ];
        }
        //视频消息
        if($msg['msg_type']['value']=='video'){
            $queryarr = [
                'mpvideo' => [
                    'media_id' => $msg['content'],
                    'title' => $msg['title'],
                    'description' => $msg['description']
                ],
                'msgtype' => 'mpvideo'
            ];
        }
        //卡券消息
        if($msg['msg_type']['value']=='wxcard'){
            $queryarr = [
                'wxcard' => [
                    'card_id' => $msg['content']
                ],
                'msgtype' => 'wxcard'
            ];
        }
        $queryarr['touser'] = $open_id;
        $access_token = $this->getAccessToken($applet_id,2);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token='.$access_token;
        $result = json_decode(Http::post($url,json_encode($queryarr)),true);
        return $result;
    }

    /**
     * 删除公众号群发记录
     */
    public function deleteMass(int $msg_id,int $applet_id = 0)
    {
        $access_token = $this->getAccessToken($applet_id,2);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token='.$access_token;
        $queryarr = ['msg_id' => $msg_id];
        $result = json_decode(Http::post($url,json_encode($queryarr)),true);
        return $result;
    }

    /**
     * 向公众号发布预览消息
     */
    public function previewMsg(array $data, string $open_id, int $applet_id = 0)
    {
        //图文消息
        if($data['msg_type']=='news'){
            $queryarr = [
                'mpnews' => ['media_id' => $data['content']],
                'msgtype' => 'mpnews'
            ];
        }
        //文本消息
        if($data['msg_type']=='text'){
            $queryarr = [
                'text' => ['content' => $data['content']],
                'msgtype' => 'text'
            ];
        }
        //语音消息
        if($data['msg_type']=='voice'){
            $queryarr = [
                'voice' => ['media_id' => $data['content']],
                'msgtype' => 'voice'
            ];
        }
        //图片消息
        if($data['msg_type']=='image'){
            $queryarr = [
                'image' => ['media_id' => $data['content']],
                'msgtype' => 'image'
            ];
        }
        //视频消息
        if($data['msg_type']=='video'){
            $queryarr = [
                'mpvideo' => ['media_id' => $data['content']],
                'msgtype' => 'mpvideo'
            ];
        }
        //卡券消息
        if($data['msg_type']=='wxcard'){
            $queryarr = '{
                "wxcard":{
                    "card_id":"'.$data['content'].'",
                    "card_ext": "{
                        "code":"",
                        "openid":"",
                        "timestamp":"",
                        "signature":""
                    }
                    "msgtype":"wxcard"
                }';
            $queryarr = [
                'wxcard' => [
                    'card_id' => $data['content'],
                    'card_ext' => [
                        'code' => '',
                        'openid' => '',
                        'timestamp' => '',
                        'signature' => ''
                    ]
                ],
                'msgtype' => 'wxcard'
            ];
        }
        $queryarr['touser'] = $open_id;
        $access_token = $this->getAccessToken($applet_id,2);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token='.$access_token;
        $result = json_decode(Http::post($url,json_encode($queryarr)),true);
        return $result;
    }

    /**
    * 公众号自定义菜单 - 同步到微信端
    */
    public function creatMenu(array $menu, int $applet_id = 0)
    {
        $access_token = $this->getAccessToken($applet_id,2);
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        $queryarr = [
           'button' => $menu
        ];
        $result = json_decode(Http::post($url, json_encode($queryarr,JSON_UNESCAPED_UNICODE)),true);
        return $result; 
    }

    /**
     * 发布模板消息 - 公众号
     */
    function sendWechatMsg(int $applet_id = 0, array $queryarr)
    {
        $access_token = $this->getAccessToken($applet_id,2);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
        $result = json_decode(Http::post($url,json_encode($queryarr)),true);
        return true; 
    }

    /**
     * 发送订阅消息
     */
    public function sedSubscribeMsg(int $applet_id, array $queryarr)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
        $result = json_decode(Http::post($url,json_encode($queryarr)),true);
        return true; 
    }

    /**
     * 启动ticket推送服务
     */
    function startTicket(string $component_appid, string $component_secret)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_start_push_ticket';
        $queryarr = [
            'component_appid' => $component_appid,
            'component_secret' => $component_secret
        ];
        Http::post($url, json_encode($queryarr));
        return true;
    }


    /**
     * 批量删除模板库中模板
     */
    public function deleteTemplateAll(int $template_id)
    {
        $config = $this->config;
        $url = 'https://api.weixin.qq.com/wxa/deletetemplate?access_token='.$config['component_access_token'];
        $queryarr = ['template_id' => $template_id];
        $result = json_decode(Http::post($url,json_encode($queryarr)),true);
        return $result;
    }
    
    /**
     * 获取代码模板列表
     */
    public function getTemplateList()
    {
        $config = $this->config;
        $url = 'https://api.weixin.qq.com/wxa/gettemplatelist?access_token='.$config['component_access_token'];
        $result = json_decode(Http::get($url),true);
        if($result['errcode']==0 AND sizeof($result['template_list']) > 0){
            return arr_sort($result['template_list'],'template_id');
        }
        return [];
    }

    /**
     * 将草稿添加到代码模板库
     */
    public function addToTemplate(int $draft_id)
    {
        $config = $this->config;
        $url = 'https://api.weixin.qq.com/wxa/addtotemplate?access_token='.$config['component_access_token'];
        $queryarr = ['draft_id' => $draft_id];
        $result = json_decode(Http::post($url,json_encode($queryarr)),true);
        return $result;
    }

    /**
     * 获取代码草稿列表
     */
    public function getTemplateDraftList()
    {
        $config = $this->config;
        $url = 'https://api.weixin.qq.com/wxa/gettemplatedraftlist?access_token='.$config['component_access_token'];
        $result = json_decode(Http::get($url),true);
        if($result['errcode']!=0 OR !isset($result['draft_list'])){
            return [];
        }
        if(sizeof($result['draft_list'])){
            return arr_sort($result['draft_list'],'draft_id');
        }
        return [];
    }


    /**
     * 生成二维码
     */
    public function getQrCode(int $applet_id, string $scene)
    {
        $path = '/temp';
        $file_name = $path . '/' . $scene . '.png';
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        $queryarr = ['scene' => $scene];
        $result = Http::post($url,json_encode($queryarr));
        if(!file_exists('.'.$path)){
            mkdir('.'.$path,0777,true);
        } 
        file_put_contents('.'.$file_name,$result); 
        //获取的二维码数据存储到指定的文件
        return $file_name;
    }

    
 
    /**
     * 公众号用户登录 - 获取用户资料
     */
    public function getTicket($applet_id)
    {
        if(!$ticket = Cache::get('jsapi_ticket_'.$applet_id)){
            $access_token = $this->getAccessToken($applet_id);
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
            $queryarr = [
                'access_token' => $access_token,
                'type' => 'jsapi'
            ];
            $result = json_decode(Http::get($url, $queryarr),true);
            if($result['errcode']!=0){
                return false;
            }
            $ticket = $result['ticket'];
            Cache::set('jsapi_ticket_'.$applet_id, $ticket, 5000);
        }
        return $ticket;
    }

	/**
	* 查询昵称设置状态
	*/
	public function querynickname(){
		$audit_id='454738159';
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/api_wxa_querynickname?access_token='.$access_token;
		$data = ['audit_id' => $audit_id];
		$result = http_post($url,$data);
		return $result;
	}
	

	/**
	* 获取审核时可填写的类目信息
	*/
	public function getshowwxaitem()
	{
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/getshowwxaitem?access_token='.$access_token;
		return curl($url);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/***************************** V5.0.0 整理*****************************************/
	
	/**
     * code换取token - 微信扫码登录
     */
    function getWebToken(string $code)
    {
        $values = Setting::getItem('wxweb',0);
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $queryarr = [
            'appid' => $values['app_id'],
            'secret' => $values['app_secret'],
            'grant_type' => 'authorization_code',
            'code' => $code
        ];
        $result = json_decode(Http::get($url,$queryarr),true);
        if(isset($result['errcode']) AND $result['errcode'] != 0){
            $this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
		    return false;
		}
		return $result;
    }
    
    /**
     * 用户登录 - 获取用户资料 (公众号，web应用)
     */
    public function getUserinfo(string $openid, string $access_token)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo';
        $queryarr = [
            'access_token' => $access_token,
            'openid' => $openid,
            'lang' => 'zh_CN'
        ];
        $result = json_decode(Http::get($url, $queryarr),true);
        if(isset($result['errcode']) AND $result['errcode'] != 0){
            $this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
		    return false;
		}
		return $result;
    }
    
    /**
     * 获取授权应用的帐号基本信息
    */
    public function getAppInfo(string $auth_appid)
    {
        $config = $this->config;
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token='.$config['component_access_token'];
        $queryarr = [
            'component_appid' => $config['app_id'],
            'authorizer_appid' => $auth_appid
        ];
        $result = json_decode(Http::post($url, json_encode($queryarr)),true);
        if(isset($result['errcode']) AND $result['errcode'] != 0){
            $this->error = 'code：'.$result['errcode'].'，msg：'.$result['errmsg'];//获取失败
            return false;
        }
        return $result;
    }
	
	/**
     * 修改小程序头像
     */
    public function modifyHeadImage(string $media_id,int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        //执行修改头像
        $url = 'https://api.weixin.qq.com/cgi-bin/account/modifyheadimage?access_token='.$access_token;
        $queryarr = [
            'head_img_media_id' => $media_id,
            'x1' => 0,
            'y1' => 0,
            'x2' => 1,
            'y2' => 1
        ];
        return $this->result(json_decode(Http::post($url, hema_json($queryarr)),true));
    }
    
	/**
    * 上传临时素材
    */
    public function upTempMaterial(string $file_url, int $applet_id, string $type='image')
    {   
        $access_token = $this->getAccessToken($applet_id);
        $real_path = web_path() . 'temp/' . time() . '.jpg';
        $temp_file = file_get_contents($file_url); //获取网络图片
        file_put_contents($real_path,$temp_file); //存放临时图片
        $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$access_token.'&type='.$type;
        $queryarr['media'] = curl_file_create($real_path,'image/jpeg',$file_url);//获取要上传的二进制文件
        $result = json_decode(http_post($url,$queryarr),true);
        unlink($real_path);//删除临时图片
        if(isset($result['media_id'])){
            return $result['media_id']; //返回的临时素材（media_id）         
        }else{
            $this->error = 'code：'.$result['errcode'].'，msg：'.$result['errmsg'];//获取失败
            return false;
        }
    }
	
	/**
     * 生成体验版二维码
     */
    public function getTestCode($applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $path = urlencode('/pages/index/index');
        $url = 'https://api.weixin.qq.com/wxa/get_qrcode?access_token='.$access_token.'&path='.$path;
        $result = Http::get($url);
        return $result;
    }
	
	/**
    * 获取小程序设置信息
    */
    public function getInfor(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/cgi-bin/account/getaccountbasicinfo?access_token='.$access_token;
        return $this->result(json_decode(Http::get($url),true));
    }
	
	/**
    * 获取预授权码 - 生成授权页面
    * $type，1=授权公众号，2=授权小程序，3=两者都有
    */
    public function authUrl(int $applet_id = 0, int $type = 3)
    {
        $config = $this->config;    //获取第三方配置
        $url = '#';
        $redirect_uri = 'https://'.$config['authorize_domain'].'/applet/auth/';
        if($type==1){
            $redirect_uri .= 'wechat/applet_id/'.$applet_id;
        }else{
            $redirect_uri .= 'wxapp/applet_id/'.$applet_id;
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$config['component_access_token'];
        $queryarr = [
            'component_appid' => $config['app_id']
        ];
        $result = json_decode(Http::post($url, json_encode($queryarr)),true);//返回"pre_auth_code": "预授权码","expires_in": 有效期（600秒）
        if(isset($result['pre_auth_code'])){
            $url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$config['app_id'].'&pre_auth_code='.$result['pre_auth_code'].'&redirect_uri='.$redirect_uri.'&auth_type='.$type;
        }
        return $url;
    }
    
    /**
     * 提交审核小程序代码
     */
    public function submitAudit(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/submit_audit?access_token='.$access_token;
        return $this->result(json_decode(Http::post($url),true));
    }

    /**
     * 发布已通过审核的小程序
     */
    public function release(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/release?access_token='.$access_token;
        return $this->result(json_decode(Http::post($url,'{}'),true)); 
    }

    /**
    * 撤回审核中的小程序
    * 单个帐号每天审核撤回次数最多不超过 1 次，一个月不超过 10 次。
    */
    public function undoCodeAudit(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/undocodeaudit?access_token='.$access_token;
        return $this->result(json_decode(Http::get($url),true));
    }
	
	/**
     * 上传小程序代码
     */
    public function publish($applet, $code, $is_live = 0) 
    {
        $access_token = $this->getAccessToken($applet['applet_id']);
        $url = 'https://api.weixin.qq.com/wxa/commit?access_token='.$access_token;
        $apiurl = $this->config['api_domain'];
        $apiurl = explode(';',$apiurl);
        $apiurl = 'https://'.$apiurl[0].'/';
        $ext = [
            'extEnable' => true,
            'extAppid' => $applet['app_id'],
            'directCommit' => false,
            'ext' => [
                'applet_id' => $applet['applet_id'],
                'api_url' => $apiurl
            ]
        ];
        //如果小程序开通直播
        if($is_live == 1){
            /*
            if($wxlive = get_addon_config('wxlive')){
                $ext['plugins'] = [
                    'live-player-plugin' => [
                        'version' => $wxlive['user_version'],
                        'provider' => $wxlive['plugin_appid']
                    ]
                ];
            }*/
        }
        $queryarr = [
            'template_id' => $code['id'],
            'ext_json' => json_encode($ext),
            'user_version' => $code['user_version'],
            'user_desc' => $code['user_desc']
        ];
        return $this->result(json_decode(Http::post($url, hema_json($queryarr)),true));
    }
	
	 /**
     * 设置服务器域名
     */
    public function setServeDomain(int $applet_id = 0, string $apiurl = '', string $access_token = '')
    {
        $config = $this->config;
        if(empty($access_token)){
            $access_token = $this->getAccessToken($applet_id);
        }
        if(empty($apiurl)){
            $apiurl = $config['api_domain'];
        }
        $domain = explode(';',$apiurl);
        $requestdomain = [];//request 合法域名
        $wsrequestdomain = [];//socket 合法域名
        for($n=0;$n<sizeof($domain);$n++){
            $requestdomain[$n] = 'https://'.$domain[$n];
            $wsrequestdomain[$n] = 'wss://'.$domain[$n];
        }
        $url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token='.$access_token;
        $queryarr = [
            'action' => 'set',
            'requestdomain' => $requestdomain,
            'wsrequestdomain' => $wsrequestdomain,
            'uploaddomain' => $requestdomain,
            'downloaddomain' => $requestdomain
        ];
        $result = json_decode(Http::post($url, hema_json($queryarr)),true);
        if($result['errcode'] != 0){
            $this->error = 'code：'.$result['errcode'].',msg：'.$result['errmsg'];
            return false;
        }
        $result['apiurl'] = $apiurl;
        return $result;
    }
    
    /**
     * 设置业务域名
     */
    public function setWebDomain(int $applet_id = 0, string $apiurl = '')
    {
		$config = $this->config;
        if(empty($access_token)){
            $access_token = $this->getAccessToken($applet_id);
        }
        if(empty($apiurl)){
            $apiurl = $config['api_domain'];
        }
        $domain = explode(';',$apiurl);
        $webviewdomain = [];
        foreach ($domain as $vo){
            $webviewdomain[] = 'https://'.$vo;
        }
		$url = 'https://api.weixin.qq.com/wxa/setwebviewdomain?access_token='.$access_token;
		$queryarr = [
			'action' => 'set',
			'webviewdomain' => $webviewdomain
		];
		return $this->result(json_decode(Http::post($url, hema_json($queryarr)),true));
    }

    /**
     * 设置功能介绍
     */
    public function setSignature(int $applet_id = 0, string $signature = '', string $access_token = '')
    {
        if(empty($access_token)){
            $access_token = $this->getAccessToken($applet_id);
        }
        if(empty($signature)){
            $signature = '一个值得信赖的小程序';
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/account/modifysignature?access_token='.$access_token;
        $queryarr = ['signature' => $signature];
        $result = json_decode(Http::post($url, hema_json($queryarr)),true);
        if($result['errcode'] != 0){
            $this->error = 'code：'.$result['errcode'].',msg：'.$result['errmsg'];
            return false;
        }
        $result['signature'] = $signature;
        return $result;
    }
	
	/**
    * 微信认证名称检测
    */
    public function checkWxVerifyNickName(int $applet_id, string $nick_name)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxverify/checkwxverifynickname?access_token='.$access_token;
        $queryarr = ['nick_name' => $nick_name];
        return $this->result(json_decode(Http::post($url, hema_json($queryarr)),true));
    }

    /**
     * 设置小程序昵称
     */
    public function setNickName(int $applet_id, string $nick_name, string $license, string $other1)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/setnickname?access_token='.$access_token;
        $queryarr = [
            'nick_name' => $nick_name,
            'license' => $license,
            'naming_other_stuff_1' => $other1
        ];
        return $this->result(json_decode(Http::post($url, hema_json($queryarr)),true));
    }
	
	/**
     * 删除类目
     */
    public function deleteCategory(int $applet_id, int $first, int $second)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/deletecategory?access_token='.$access_token;
        $queryarr = [
            'first' => $first,
            'second' => $second
        ];
        return $this->result(json_decode(Http::post($url, hema_json($queryarr)),true));
    }
	
	/**
    * 获取已设置的所有类目
    */
    public function getCategory(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/getcategory?access_token='.$access_token;
        $result = json_decode(Http::get($url),true);
        return $result;
    }
    
    /**
     * 获取可以设置的所有类目
     */
    public function getAllCategories($applet_id)
    {
        //同步微信端线下类目
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/getallcategories?access_token='.$access_token;
        $result = json_decode(Http::get($url),true);
        if($result['errcode']==0){
            $category = $result['categories_list']['categories'];
            $new = []; //筛选后的类目
            //遍历一级类目
            foreach($category[0]['children'] as $value){
                //查找一级类目
                for($n=1;$n<sizeof($category);$n++){
                    //如果找到该一级目录
                    if($category[$n]['id']==$value){ 
                        //判断是否有二级目录
                        if(sizeof($category[$n]['children'])){
                            $first['id'] = $category[$n]['id'];
                            $first['name'] = $category[$n]['name'];
                            //遍历二级目录
                            $second = [];
                            foreach($category[$n]['children'] as $value2){
                                //查找二级目录
                                for($m=$n;$m<sizeof($category);$m++){
                                    //如果找到该一级目录
                                    if($category[$m]['id']==$value2){
                                        $category[$m]['father_name'] = $category[$n]['name'];
                                        array_push($second,$category[$m]);
                                        break;
                                    } 
                                }
                            }
                            //如果存在可用二级目录
                            if(sizeof($second)){
                                $first['children'] = $second;
                                array_push($new,$first);
                                break;
                            }
                        }
                        
                    }
                }
            }
            return $new;//返回类目结果
        }
        return 'code：'.$result['errcode'].'，msg：'.$result['errmsg'];//获取失败
    }
    
    /**
     * 添加类目
     */
    public function addCategory(int $applet_id, int $first,int $second,string $ca_name = '',string $media_id = '')
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/addcategory?access_token='.$access_token;
        $queryarr = [
            'categories' => [
                [
                    'first' => $first,
                    'second' => $second,
                    'certicates' => [
                        'key' => $ca_name,
                        'value' => $media_id
                    ]
                ]
            ]
        ];
        return $this->result(json_decode(Http::post($url, hema_json($queryarr)),true));
    }
	
	/**
    * 附近小程序 - 查询地点类目信息
    */
    public function getStoreWxaAttr(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/getstorewxaattr?access_token='.$access_token;
        $result = json_decode(Http::get($url),true);
        $list = [];
        if($result['errcode'] == 0 AND $result['is_exist'] == 1){
            $category = $this->getMerchantCategory($applet_id);//拉取可设置类目
            if(isset($result['store_wxa_attr']['weapp_category'])){
                foreach ($result['store_wxa_attr']['weapp_category']['categories'] as $vo) {
                    $first_name = '';
                    $second_name = '';
                    //获取一级类目名称
                    foreach ($category as $first) {
                        if($first['id'] == $vo['first']){
                            $first_name = $first['name'];
                            //获取二级类目名称
                            foreach ($first['children'] as $second) {
                                if($second['id'] == $vo['second']){
                                    $second_name = $second['name'];
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    $list[] = [
                        'first_id' => $vo['first'],
                        'first_name' => $first_name,
                        'second_id' => $vo['second'],
                        'second_name' => $second_name,
                        'audit_status' => $vo['audit_status'],
                        'audit_id' => $vo['audit_id']
                    ];
                }
            }
        }
        return $list;
    }

    /**
    * 附近小程序 - 申请附近地点类目
    */
    public function nearbyApplyCategory(array $queryarr, int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/nearbyapplycategory?access_token='.$access_token;
        $this->result(json_decode(Http::post($url,hema_json($queryarr)),true));
    }

    /**
    * 附近小程序 - 拉取门店小程序类目
    */
    public function getMerchantCategory(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/get_merchant_category?access_token='.$access_token;
        $result = json_decode(Http::get($url),true);
        if($result['errcode']==0){
            $category = $result['data']['all_category_info']['categories'];
            $new = []; //筛选后的类目
            //遍历一级类目
            foreach($category[0]['children'] as $value){
                //查找一级类目
                for($n=1;$n<sizeof($category);$n++){
                    //如果找到该一级目录
                    if($category[$n]['id']==$value){ 
                        //判断是否有二级目录
                        if(sizeof($category[$n]['children'])){
                            $children = [];
                            foreach ($category[$n]['children'] as $value2) {
                                //查找二级类目
                                for($m=1;$m<sizeof($category);$m++){
                                    //如果找到该一级目录
                                    if($category[$m]['id']==$value2){
                                        $children[] = $category[$m];
                                        continue;
                                    }
                                }
                            } 
                            $category[$n]['children'] = $children;
                        }
                        $new[] = $category[$n];  
                        continue;
                    }
                }
            }
            return $new;//返回类目结果
        }
        return 'code：'.$result['errcode'].'，msg：'.$result['errmsg'];//获取失败
    }

    /**
    * 附近小程序 - 获取附近门店列表
    */
    public function getNearbyPoi(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/getnearbypoilist?page=1&page_rows=20&access_token='.$access_token;
        $result = json_decode(Http::get($url),true);
        return $result;
    }

    /**
    * 附近小程序 - 添加附近门店
    */
    public function addNearbyPoi(array $queryarr, int $applet_id)
    {
        $queryarr['hour'] = str_replace(' ','',$queryarr['hour']);
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/addnearbypoi?access_token='.$access_token;
        return $this->result(json_decode(Http::post($url,hema_json($queryarr)),true));
    }

    /**
    * 附近小程序 - 删除附近门店
    */
    public function delNearbyPoi(int $applet_id, string $poi_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/delnearbypoi?access_token='.$access_token;
        $queryarr =[
            'poi_id' => $poi_id //门店的 poi_id 
        ];
        return $this->result(json_decode(Http::post($url,hema_json($queryarr)),true));
    }
    
    /**
    * 附近小程序 - 展示/取消展示附近门店（小程序）
    */
    public function setNearbyPoiShowStatus(int $applet_id, $poi_id, $status)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/setnearbypoishowstatus?access_token='.$access_token;
        $queryarr =[
            'poi_id' => $poi_id, //门店的 poi_id 
            'status' => $status //0：取消展示；1：展示
        ];
        return $this->result(json_decode(Http::post($url,hema_json($queryarr)),true));
    }
    
    /**
    * 配置小程序用户隐私保护指引
    */
    public function setPrivacySetting($applet_id,$data)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/cgi-bin/component/setprivacysetting?access_token=' . $access_token;
        $queryarr =[
            'owner_setting' => [
                'contact_email' => $data['contact_email'],//第三方联系邮箱   
                'notice_method' => '小程序弹窗'
            ],
            'setting_list' => [
                [
                    'privacy_key' => 'UserInfo',
                    'privacy_text' => '用于展示用户信息'
                ],
                [
                    'privacy_key' => 'Location',
                    'privacy_text' => '用于计算到店距离'
                ],
                [
                    'privacy_key' => 'Address',
                    'privacy_text' => '用于获取配送地址'
                ],
                [
                    'privacy_key' => 'PhoneNumber',
                    'privacy_text' => '用于办理会员卡'
                ]
            ]
        ];
        return $this->result(json_decode(Http::post($url,hema_json($queryarr)),true));
        
    }
    
    /**
    * 查询小程序用户隐私保护指引
    */
    public function getPrivacySetting($applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/cgi-bin/component/getprivacysetting?access_token=' . $access_token;
        return $this->result(json_decode(Http::post($url,"{}"),true));
        
    }
    
    /**
    * 获取体验用户列表
    */
    public function getTestUser(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/memberauth?access_token='.$access_token;
        $queryarr =[
            'action' => 'get_experiencer' //固定值
        ];
        return json_decode(Http::post($url,hema_json($queryarr)),true);
    }

    /**
    * 添加体验用户
    */
    public function addTestUser(int $applet_id, string $wechatid)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/bind_tester?access_token='.$access_token;
        $queryarr =[
            'wechatid' => $wechatid //微信号
        ];
        return $this->result(json_decode(Http::post($url,hema_json($queryarr)),true));
    }

    /**
    * 删除体验用户
    */
    public function delTestUser(int $applet_id, string $userstr)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxa/unbind_tester?access_token='.$access_token;
        $queryarr =[
            'userstr' => $userstr //唯一识别码
        ];
        return $this->result(json_decode(Http::post($url,hema_json($queryarr)),true));
    }
    
    /**
     * 上传图文消息内的图片 - 到微信端（永久素材） - 小程序端
     *  图片仅支持jpg/png格式，大小必须在1MB以下
     */
    public function upMediaUrl(string $file_url, int $applet_id = 0)
    {
        $access_token = $this->getAccessToken($applet_id);
        $real_path = web_path() . 'temp/' . time() . '.jpg';
        $temp_file = file_get_contents($file_url);//获取网络图片
        file_put_contents($real_path,$temp_file); //存放临时图片
        //上传到微信服务器
        $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token='.$access_token;
        $queryarr['media'] = curl_file_create($real_path,'image/jpeg',$file_url);//获取要上传的二进制文件
        $result = json_decode(Http::post($url,$queryarr),true);
        unlink($real_path);//删除临时图片
        if(!isset($result['url'])){
            $this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
            return false;//上传错误，一般是图片不符合要求
        }
        return $result['url'];
    }
    
    /**
     * 添加帐号下的模板
     */
    public function addTemplateTpl(int $applet_id, string $tid, array $kidlist, string $desc)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token='.$access_token;
        $queryarr = [
            'tid' => $tid,
            'kidList' => $kidlist,
            'sceneDesc' => $desc
        ];
        return $this->result(json_decode(Http::post($url, hema_json($queryarr),[],['content-type: application/json']),true));
    }
    
    /**
     * 删除帐号下的模板
     */
    public function delTemplateTpl(int $applet_id, string $tpl_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate?access_token='.$access_token;
        $queryarr = [
            'priTmplId' => $tpl_id
        ];
        return $this->result(json_decode(Http::post($url, hema_json($queryarr)),true));
    }

    /**
     * 获取帐号下的模板列表
     */
    public function getTemplateTpl(int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id);
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token='.$access_token;
        return $this->result(json_decode(Http::get($url),true));
    }
    
    /**
     * 使用授权码获取授权信息
    */
    public function getAuth(string $auth_code)
    {
        $config = $this->config;
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.$config['component_access_token'];
        $queryarr = [
            'component_appid' => $config['app_id'],
            'authorization_code' => $auth_code
        ];
        $result = json_decode(Http::post($url, hema_json($queryarr)),true);
        if(!isset($result['authorization_info'])){
            $this->error = 'code：' . $result['errcode'] . ' msg：' . $result['errmsg'];
            return false;
        }
        return $result['authorization_info'];
    }
    
    /**
     * 获取 component_access_token
    */
    public function getComponentToken(string $ticket)
    {
        $config = $this->config;
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
        $queryarr = [
            'component_appid' => $config['app_id'],
            'component_appsecret' => $config['app_secret'],
            'component_verify_ticket' => $ticket,
        ];
        $result = json_decode(Http::post($url, hema_json($queryarr)),true);
        if(isset($result['component_access_token'])){
			return $result;
		}
		$this->error = 'code：' . $result['errcode'] . ' msg：' . $result['errmsg'];
        return false;
    }
    
    /**
     * 获取公众号粉丝用户基本信息（包括UnionID机制）- 公众号
    */
    public function getWechatUserInfo(string $openid, int $applet_id)
    {
        $access_token = $this->getAccessToken($applet_id,2);
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info';
        $queryarr = [
            'access_token' => $access_token,
            'openid' => $openid,
            'lang' => 'zh_CN'
        ];
        $result = json_decode(Http::get($url,$queryarr),true);
        if(!isset($result['openid'])){
            $this->error = 'code：' . $result['errcode'] . ' msg：' . $result['errmsg'];
            return false;
        }
        $union_id = '';
        if(isset($result['unionid'])){
            $union_id = $result['unionid'];
        }
        return [
            'union_id' => $union_id,
            'open_id' => $result['openid'],
            'nickname' => preg_replace('/[\xf0-\xf7].{3}/', '', $result['nickname']),
            'avatar' => $result['headimgurl'],
            'gender' => $result['sex'],
            'country' => $result['country'],
            'province' => $result['province'],
            'city' => $result['city']
        ];
    }
    
    /**
     * 发送客服消息模板
    */
    public function sendServiceMsg(array $msg, string $touser, int $applet_id)
    {
        //文本消息
        if($msg['type']=='text'){
            $queryarr = [
                'msgtype' => 'text',
                'text' => [
                    'content' => $msg['content']
                ]
            ];
        }
        //图片消息
        if($msg['type']=='image'){
            $queryarr = [
                'msgtype' => 'image',
                'image' => [
                    'media_id' => $msg['media_id']
                ]
            ];
        }
        //图文消息（点击跳转到图文消息页面） 图文消息条数限制在1条以内
        if($msg['type']=='news'){
            $queryarr = [
                'msgtype' => 'mpnews',
                'mpnews' => [
                    'media_id' => $msg['media_id']
                ]
            ];
        }
        //发送图文消息（点击跳转到外链） 图文消息条数限制在1条以内
        if($msg['type']=='news'){
            $queryarr = [
                'msgtype' => 'news',
                'news' => [
                    'articles' => [
                        'picurl' => $msg['picurl'],
                        'url' => $msg['url'],
                        'title' => $msg['title'],
                        'description' => $msg['description']
                    ]
                ]
            ];
        }
        //语音消息
        if($msg['type']=='voice'){
            $queryarr = [
                'msgtype' => 'voice',
                'voice' => [
                    'media_id' => $msg['media_id']
                ]
            ];
        }
        //视频消息
        if($msg['type']=='video'){
            $queryarr = [
                'msgtype' => 'video',
                'video' => [
                    'media_id' => $msg['media_id'],
                    'thumb_media_id' => $msg['thumb_media_id'],
                    'title' => $msg['title'],
                    'description' => $msg['description']
                ]
            ];
        }
        //音乐消息
        if($msg['type']=='music'){
            $queryarr = [
                'msgtype' => 'music',
                'video' => [
                    'musicurl' => $msg['musicurl'],
                    'thumb_media_id' => $msg['thumb_media_id'],
                    'title' => $msg['title'],
                    'hqmusicurl' => $msg['hqmusicurl'],
                    'description' => $msg['description']
                ]
            ];
        }

        //发送小程序卡片（要求小程序与公众号已关联）
        if($msg['type']=='wxapp'){
            $queryarr = [
                'msgtype' => 'miniprogrampage',
                'miniprogrampage' => [
                    'pagepath' => $msg['pagepath'],
                    'thumb_media_id' => $msg['thumb_media_id'],
                    'title' => $msg['title'],
                    'appid' => $msg['appid'],
                    'description' => $msg['description']
                ]
            ];
        }
        if(isset($queryarr)){
            $queryarr['touser'] = $touser;
            $access_token = $this->getAccessToken($applet_id,2);
            $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
            return $this->result(json_decode(Http::post($url, hema_json($queryarr)),true));
        }
        return false;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    /**
     * 获取令牌 - 开放平台
     * $type 请求类型 1小程序，2公众号
    */
    function getAccessToken(int $applet_id = 0, int $type = 1)
    {
        $config = $this->config;    //获取第三方配置
        if($type==1){
            $applet = Applet::getApplet(['applet_id' => $applet_id]);
            $access_token=$applet['access_token'];
            if($applet['expires_in'] < time()){
                //重新获取
                $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$config['component_access_token'];
                $queryarr = [
                    'component_appid' => $config['app_id'],
                    'authorizer_appid' => $applet['app_id'],
                    'authorizer_refresh_token' => $applet['authorizer_refresh_token']
                ];
                $result = json_decode(Http::post($url, json_encode($queryarr)),true);
                if(isset($result['authorizer_access_token'])){
                    $access_token = $result['authorizer_access_token'];
                    $applet->access_token = $result['authorizer_access_token'];
                    $applet->expires_in = time()+3600; //2个小时候过期，这里设置1小时获取一次
                    $applet->save();//保存最新的令牌access_token和过期时间
                }
            }
        }else{
            //公众号
            $wechat = Wechat::getWechat(['applet_id' => $applet_id]);    //获取第三方配置
            $access_token=$wechat['access_token'];
            if($wechat['expires_in'] < time()){
                //重新获取
                $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$config['component_access_token'];
                $queryarr = [
                    'component_appid' => $config['app_id'],
                    'authorizer_appid' => $wechat['app_id'],
                    'authorizer_refresh_token' => $wechat['authorizer_refresh_token']
                ];
                $result = json_decode(Http::post($url, json_encode($queryarr)),true);
                if(isset($result['authorizer_access_token'])){
                    $access_token = $result['authorizer_access_token'];
                    $wechat->access_token = $result['authorizer_access_token'];
                    $wechat->expires_in = time()+3600; //2个小时候过期，这里设置1小时获取一次
                    $wechat->save();//保存最新的令牌access_token和过期时间
                }
            }           
        }
        return $access_token;
    }
    
    /**
     * 请求数据验证
     **/
    private function result($result)
    {
        if($result['errcode']!=0){
			$this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
			return false;
		}
		return $result;
    }
    
    public function getError()
    {
        return $this->error;
    }

}